package GUI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Vector;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowSorter;
import javax.swing.SpringLayout;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

import CommonGui.NotEdditibleTable;
import DataObjects.BusinessMenuRightList;
import DataObjects.ConstantObjects;
import DataObjects.RecipeLeftList;
import DataObjects.RecipeRightList;
import Messages.MessageAddRecipeToDataBase;
import Messages.MessageGetAllItemsForNewRecipe;
import Messages.MessageGetAllItemsForNewRecipeReply;
import Messages.MessageGetAllRecipes;
import Messages.MessageGetAllRecipesReply;
import Messages.MessageGetItemsByCategory;
import Messages.MessageGetItemsByCategoryForNewRecipe;
import Messages.MessageGetItemsByCategoryForNewRecipeReply;
import Messages.MessageGetItemsByCategoryReply;
import Messages.MessageGetPriceItemByNameItem;

import Messages.MessageGetPriceItemByNameItemReply;
import Messages.MessageSavingReply;
import Messages.MessageShowAllStandardsMenus;
import Messages.MessageShowAllStandardsMenusReply;
import Messages.MessageShowIDInventoryItem;
import Messages.MessageShowIDInventoryItemReply;
import Messages.MessageShowIDRecipe;
import Messages.MessageShowIDRecipeReply;

/**
 * 
 * @author Andrey,Igor
 * Class for addition new recipe to DB 
 *
 */
public class PfAdd_new_recipe extends JPanel{
	
	private int flagChange=0;
	private int count_res_menuRecipes=0;
	private int mId;
	private float price;
	private float totalPrice;
	private float totalWeight=0;
	private String flag;
	private JComboBox statusRecipe;
	
	private JTextField itemTxt;
	private JTextField medidaTxt;
	private JTextField weightTxt;
	private JTextField	costTxt;
	private JTextField textField_RecipeId;
	private JTextField	textField_nameRecipe;
	private JTextField textField_price;
	private JTextField costItemTxt;
	private JTextField reallyCostItemTxt;
	private JTextField nameTF1;
	private JTextField nameTF2;
	private JTextField mishkalTxt;
	private JTextField mishkalMatkon;
	
	private RowSorter<DefaultTableModel> sorterName;
	
	
	private String menuId;
	private MainMenu mainMenu;
	
	private JPanel totalPanel;
	private JPanel bulkiPanel;
	private JPanel leftPanel;
	private JPanel rightPanel;
	private JPanel detailsPanel;
	private JPanel tablePanel;
	private JPanel allItemsPanel;
	private JPanel greatMiddlePanel;
	private JPanel	greatButtonsCategoryPanel;
	private JPanel middlePanel;
	private JPanel suppItemsPanel;
	private JPanel  allItemsListPanel;
	private JPanel allItemsPanelSearch;
	private JPanel recipeItemsPanelSearch;
	private JPanel recipeItemsListPanel;
	private JPanel buttonsPanel;
	private JPanel costRecipePanel;
	
	private JList allItemsList;
	private JList menuItemsList;
	private DefaultListModel allItemsModel;
	private DefaultListModel recipeItemsModel;
	
	private Vector<RecipeLeftList> res_allItemsTemp;
	private Vector<RecipeLeftList> res_allItems;                 
	private Vector<RecipeRightList> res_recipeItems; 

	private JButton buttInc;
	private JButton buttDec;
	private JButton leftButton;
	private JButton rightButton;
	
	private JTable tbl;
	private NotEdditibleTable dtm;
	private Component horizontalGlue;
	private Vector <String> tblheader;
	
	private int x;
	private int y;
	private Dimension screenSize;
	
	private  Vector<String> options;
	private PfAdd_options_for_recipe addItem;
	
	private DefaultTableCellRenderer centerRenderer;
	


	public PfAdd_new_recipe (MainMenu mm)
	{
		super() ;
		screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		this.mainMenu=mm;
		this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
		initialize();
	}

	
	private void initialize()
	{
		x=screenSize.width;
		y=screenSize.height;
		System.out.println("X=" +x);
		System.out.println("Y=" +y);
		add(getLeftPanel());
		add(getRightPanel());
		
	}
	
	//====================== panels for leftPanel	========================================
	/**
	 * Method for creation Panel(LeftPanel) that includes two panel(BulkiPanel - for two JLists and buttons
	 *                                                             and CostRecipePanel - to show total cost of recipes that selected) 
	 * @return JPanel leftPanel
	 */	
	private JPanel getLeftPanel()            
	{
		leftPanel=new JPanel();
		leftPanel.setBorder(new TitledBorder(null, "תבנית לבניית מתכון ", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
		leftPanel.add(getBulkiPanel());
		leftPanel.add(getCostRecipePanel());
		return leftPanel;
	}
	
	/**
	 * Method getCostRecipePanel need to creating panel with  TextField that show total cost of selected items
	 * @return JPanel costRecipePanel
	 */	
	private JPanel	getCostRecipePanel()
	{		
		costRecipePanel=new JPanel();
		GridBagLayout gbll = new GridBagLayout();    
		costRecipePanel.setLayout(gbll);
		GridBagConstraints gbc1 = new GridBagConstraints();
		GridBagConstraints gbc2 = new GridBagConstraints();
		
		gbc1.anchor = GridBagConstraints.NORTHWEST; 
		gbc1.fill   = GridBagConstraints.NONE;  
		gbc1.gridheight = 1;
		gbc1.gridwidth  = 1;
		gbc1.gridx = GridBagConstraints.RELATIVE; 
		gbc1.gridy = GridBagConstraints.RELATIVE; 
		gbc1.insets = new Insets(10, 10, 20, 0);
		
	
		
		gbc2.gridheight=1;
		gbc2.gridwidth=0;
		gbc2.insets = new Insets(0,x/4,0,0);                   //400
		
		JLabel totalCostLbl=new JLabel("סה''כ עלות:");
		JLabel totalWeightLbl=new JLabel("סה''כ משקל:");
		
		
		costRecipePanel.add(getCostTxt(),gbc1);
		costRecipePanel.add(totalCostLbl,gbc1);
		costRecipePanel.add(getMishkalTxt(),gbc1);
		costRecipePanel.add(totalWeightLbl,gbc1);
	return costRecipePanel;
		
	}
	
	/**
	 * Method getCostTxt for creation of  TextField that show total cost of selected items.Used by method getCostRecipePanel
	 * @return
	 */
	private JTextField getCostTxt()
	{
		costTxt=new JTextField();
		costTxt.setHorizontalAlignment(JTextField.RIGHT);
		costTxt.setColumns(10);
		costTxt.setEditable(false);
	return costTxt;
	}
	
	/**
	 * Method getMishkalTxt for creation of  TextField that show total mishkal of selected items.Used by method getCostRecipePanel
	 * @return
	 */
	
	private JTextField getMishkalTxt()
	{
	    mishkalTxt=new JTextField();
		mishkalTxt.setHorizontalAlignment(JTextField.RIGHT);
		mishkalTxt.setColumns(10);
		mishkalTxt.setEditable(false);
	return mishkalTxt;
	}
	
	/**
	 * Method  for creation  of panel that includes three panels(AllItemsPanel,GreatMiddlePanel,RecipeItemsPanel)
	 * @return JPanel bulkiPanel
	 */
	private JPanel getBulkiPanel()
	{
		bulkiPanel=new JPanel();
		bulkiPanel.setLayout(new BoxLayout(bulkiPanel, BoxLayout.X_AXIS));
		bulkiPanel.add(getAllItemsPanel());        
		bulkiPanel.add(getGreatMiddlePanel());;         
		bulkiPanel.add(getRecipeItemsPanel());
	return bulkiPanel;
	}
	
	/**
	 * Method for creation of panel with two panels:the first (AllItemsPanelSearch(searchTxt+searchLbl))for a quickly search (filters)
	 *   and the second panel for a list of all items that has a restaurant( ListAllItemsPanel)
	 * @return JPanel allItemsPanel
	 */
	private JPanel getAllItemsPanel()   
	{
		allItemsPanel=new JPanel();
		allItemsPanel.setLayout(new BoxLayout(allItemsPanel, BoxLayout.Y_AXIS));
		allItemsPanel.add(getAllItemsPanelSearch());
		allItemsPanel.add(getListAllItemsPanel());		
	return allItemsPanel;

	}
	
	/**
	 * Method for creation of panel that includes JList and inserts all items  that restaurant has into it.
	 * @return JPanel allItemsListPanel
	 */	
	private JPanel getListAllItemsPanel ()         
	{
		
		allItemsListPanel=new JPanel();
		 res_allItemsTemp=new Vector<RecipeLeftList>();
		allItemsListPanel.setBounds(x/33, y/33,x/3 , y/5);            //50,50,520,320
		allItemsListPanel.setLayout(new BoxLayout(allItemsListPanel, BoxLayout.X_AXIS));	
		allItemsModel=new DefaultListModel();
		
		MessageGetAllItemsForNewRecipe allItems=new MessageGetAllItemsForNewRecipe();
		try {
			mainMenu.ms.client.sendToServer(allItems);
			MessageGetAllItemsForNewRecipeReply result = (MessageGetAllItemsForNewRecipeReply)mainMenu.ms.client.GetMessage();
			this.res_allItems= result.getRecipes();
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		
		int size_vector=res_allItems.size();		
		for(int i=0;i<size_vector;i++) 
		{
			allItemsModel.addElement((String) res_allItems.get(i).getItemName());          //Enter all items's names to listmodel
		}
		
		allItemsList = new JList(allItemsModel);
		allItemsList.setBounds(0, 0, 500, 300);
		allItemsList.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		allItemsList.setFont(new Font("Tahoma", Font.PLAIN, 14));                               //*************************************************
		allItemsList.setBackground(new Color(230, 230, 250));
		JScrollPane listScroller1 = new JScrollPane(allItemsList);
		listScroller1.setPreferredSize(new Dimension(200, 600));
		allItemsListPanel.add(listScroller1);
		String selectedItem=(String)allItemsList.getSelectedValue();
		allItemsList.addListSelectionListener(new ListSelectionListener() 
	 	{
	 	      public void valueChanged(ListSelectionEvent evt) {
	 	        if (evt.getValueIsAdjusting())
	 	        return;
	 	           
	 	      JList itemList=(JList) evt.getSource();
	          String value=(String) itemList.getSelectedValue();
	          
	          int index=allItemsList.getSelectedIndex();
	          menuItemsList.clearSelection();
	          allItemsList.setSelectedIndex(index);
	          
	          itemTxt.setText(value);
	          costItemTxt.setText("");
	          weightTxt.setText("");
	          medidaTxt.setText("");
	          
	          for(int i=0;i<res_allItems.size();i++) 
	  		{
	        	  
	        	  if(value==(null))
	        		  break;
	  			if(value.equals(res_allItems.get(i).getItemName()))
	  			{
	  				
	  				medidaTxt.setText((String)res_allItems.get(i).getIUnit_of_measure());
	  				reallyCostItemTxt.setText(Float.toString(res_allItems.get(i).getiCost()));
	  				reallyCostItemTxt.setEditable(false);
	  				buttDec.setEnabled(true);
	           		buttInc.setEnabled(true);
	  				break;
	  			}
	  		}
	          
	 	       
	 	   
	 	      }
	 	    });
		
	
		return allItemsListPanel;
	}
	
	/**
	 * Method for creation JText filters to quick searching of item by name(filters)
	 * @return  JPanel allItemsPanelSearch
	 * 
	 */
	private JPanel getAllItemsPanelSearch()               
	{
				
		allItemsPanelSearch=new JPanel();
		allItemsPanelSearch.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
		//allItemsPanelSearch.setLayout(new BoxLayout(allItemsPanelSearch, BoxLayout.X_AXIS));
		JLabel searchLbl=new JLabel(":חיפוש לפי שם המוצר");
		allItemsPanelSearch.add(getButtonAddItem());
		allItemsPanelSearch.add(getNameTF1());
		allItemsPanelSearch.add(searchLbl);
		
		return allItemsPanelSearch;
	}
	
	private JButton getButtonAddItem()
	{
		JButton buttAddItem = new JButton("הוסיף פריט");
		buttAddItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				MessageShowIDInventoryItem msgShowID = new MessageShowIDInventoryItem();

				try {
					mainMenu.ms.client.sendToServer(msgShowID);
					MessageShowIDInventoryItemReply resultID = (MessageShowIDInventoryItemReply) mainMenu.ms.client
							.GetMessage();
				
				PfAdd_new_item_from_new_recipe addItem = new PfAdd_new_item_from_new_recipe(mainMenu,resultID.getResultID(),res_allItems,allItemsModel);
						
			}
				catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		
		return buttAddItem;
	}
	
	
	
	private JTextField getNameTF1()
	{
		nameTF1=new JTextField(20);
		nameTF1.setHorizontalAlignment(JTextField.RIGHT);
	
		KeyListener keyListener = new KeyListener() 
		{		      
			public void keyPressed(KeyEvent arg0) {}

			public void keyReleased(KeyEvent arg0) 
			{
				JTextField nameField = (JTextField)arg0.getSource();
				
					String selectedName = (String)nameField.getText();
				
				
				filterByName1(selectedName);				
			}

			public void keyTyped(KeyEvent arg0) {}		
		};
		
		nameTF1.addKeyListener(keyListener);		
		return nameTF1;
	}
	
	//filter for all items list
	private void filterByName1(String str)
	{
		allItemsModel.clear();
		for(int i=0;i<res_allItems.size();i++)
		{
			if(((String)res_allItems.get(i).getItemName()).startsWith(str))
			allItemsModel.addElement((String) res_allItems.get(i).getItemName());  
		}
	}
	/**
	 * Method for creation panel that includes two panels(RecipeItemsPanelSearch,ListRecipeItemsPanel)
	 * @return JPanel suppItemsPanel
	 */	
	private JPanel getRecipeItemsPanel()               
	{
		suppItemsPanel=new JPanel();
		suppItemsPanel.setLayout(new BoxLayout(suppItemsPanel, BoxLayout.Y_AXIS));
		suppItemsPanel.add(getRecipeItemsPanelSearch());
		suppItemsPanel.add(getListRecipeItemsPanel());
		return suppItemsPanel;
	}
	
	/**
	 * Method for creation of panel that includes JList and inserts all items that selected into it.
	 * @return JPanel recipeItemsListPanel
	 */
	private JPanel getListRecipeItemsPanel ()          
	{
				
		recipeItemsListPanel=new JPanel();
		recipeItemsListPanel.setLayout(new BoxLayout(recipeItemsListPanel, BoxLayout.X_AXIS));	
		recipeItemsModel=new DefaultListModel();
		menuItemsList = new JList(recipeItemsModel);
		menuItemsList.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		menuItemsList.setFont(new Font("Tahoma", Font.PLAIN, 14));
		menuItemsList.setBackground(new Color(230, 230, 250));
		JScrollPane listScroller2 = new JScrollPane(menuItemsList);
		listScroller2.setPreferredSize(new Dimension(200, 600));             //????
		recipeItemsListPanel.add(listScroller2);
		
		menuItemsList.addListSelectionListener(new ListSelectionListener() 
	 	{
	 	      public void valueChanged(ListSelectionEvent evt) {
	 	        if (evt.getValueIsAdjusting())
	 	        return;
	 	      	     
	 	      JList itemList=(JList) evt.getSource();
	          String value=(String) itemList.getSelectedValue();
	          int index=menuItemsList.getSelectedIndex();
	          
	          allItemsList.clearSelection();
	          menuItemsList.setSelectedIndex(index);
	          
	          itemTxt.setText(value);
	         
	          while(count_res_menuRecipes<res_recipeItems.size()){
	        	 
	        	  if(value==(null))
	        		  break;
           	   if(value.equals(res_recipeItems.get(count_res_menuRecipes).getItemName())){
           		
           		medidaTxt.setText((String) res_recipeItems.get(count_res_menuRecipes).getiUnit_of_measure());  
           		costItemTxt.setText(Float.toString( res_recipeItems.get(count_res_menuRecipes).getiReallyCost()));
           		weightTxt.setText(Float.toString( res_recipeItems.get(count_res_menuRecipes).getiQuantity()));
           		reallyCostItemTxt.setText(Float.toString( res_recipeItems.get(count_res_menuRecipes).getiCost()));
           		
           		medidaTxt.setEditable(false);
           		itemTxt.setEditable(false);
           		reallyCostItemTxt.setEditable(false);
           		break;
           		
           	   }
	          count_res_menuRecipes++;
	          }
	          count_res_menuRecipes=0;
	 	      mainMenu.validate();
	 	      }
	 	    });
		
	return recipeItemsListPanel;
	}
	
	/**
	 * Method for creation JTextFields filters to quick searching of item by name(filters)
	 * @return  JPanel recipeItemsPanelSearch
	 * 
	 */
	private JPanel getRecipeItemsPanelSearch()                    
	{
		recipeItemsPanelSearch=new JPanel();
		//recipeItemsPanelSearch.setLayout(new BoxLayout(recipeItemsPanelSearch, BoxLayout.X_AXIS));
		recipeItemsPanelSearch.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
		JLabel searchLbl=new JLabel("חיפוש לפי שם המוצר :");
		recipeItemsPanelSearch.add(getNameTF2());
		recipeItemsPanelSearch.add(searchLbl);
		
	return recipeItemsPanelSearch;
	}
	
	private JTextField getNameTF2()
	{
		nameTF2=new JTextField(20);
		nameTF2.setHorizontalAlignment(JTextField.RIGHT);
	
		KeyListener keyListener = new KeyListener() 
		{		      
			public void keyPressed(KeyEvent arg0) {}

			public void keyReleased(KeyEvent arg0) 
			{
				JTextField nameField = (JTextField)arg0.getSource();
				String selectedName = (String)nameField.getText();
				filterByName2(selectedName);				
			}

			public void keyTyped(KeyEvent arg0) {}		
		};
		
		nameTF2.addKeyListener(keyListener);		
		return nameTF2;
	}
	
	//filter for all items list
	private void filterByName2(String str)
	{
		recipeItemsModel.clear();
		for(int i=0;i<res_recipeItems.size();i++)
		{
			if(((String)res_recipeItems.get(i).getItemName()).startsWith(str))
				recipeItemsModel.addElement((String) res_recipeItems.get(i).getItemName());  
		}
	}
	
	
	/**
	 * Method for creation panel that includes two panels(ButtonsCategoryPanel and MiddlePanel)
	 * @return greatMiddlePanel
	 */
	private JPanel getGreatMiddlePanel()
	{
		greatMiddlePanel=new JPanel();
	    greatMiddlePanel.setLayout(new BoxLayout(greatMiddlePanel, BoxLayout.Y_AXIS));	
	//	greatMiddlePanel.add(getButtonsCategoryPanel());
		greatMiddlePanel.add(getMiddlePanel());
		return greatMiddlePanel;
	}
	
	/**
	 * Method for creation panel that includes buttons of category of items(fruits,vegetables,wine and other...).
	 * @return greatButtonsCategoryPanel
	 */
	/*private JPanel getButtonsCategoryPanel()
	{
		greatButtonsCategoryPanel=new JPanel();
		GridLayout grid =new GridLayout(0, 3, 7, 7);
		greatButtonsCategoryPanel.setLayout(grid);
		ConstantObjects consobj=new ConstantObjects();
		String [] categories=consobj.getItemCategories();
		for(int i=0; i<categories.length;i++)
		{
			greatButtonsCategoryPanel.add(getCategoryButton(categories[i]));
		}
		return greatButtonsCategoryPanel;
	}
	*/
	
	/**
	 * Method for creation JButton catButt for sorting all the items by  this category
	 * @return JButton catButt
	 */	
	/*private JButton getCategoryButton(String name)
	{
		//if(name=="פרות")
		JButton catButt=new JButton(name);
		catButt.setPreferredSize(new Dimension(80,80));
		catButt.setBackground(new Color(180,216,230));
		
		catButt.setFont(new Font("Tahoma", Font.BOLD, 14));
		catButt.addActionListener(new java.awt.event.ActionListener() 
		   {
			public void actionPerformed(java.awt.event.ActionEvent ebutt) 
			{
				JButton butt=(JButton) ebutt.getSource();
				MessageGetItemsByCategoryForNewRecipe getItems=new MessageGetItemsByCategoryForNewRecipe(butt.getText());
				try {
					mainMenu.ms.client.sendToServer(getItems);	
					MessageGetItemsByCategoryForNewRecipeReply result=(MessageGetItemsByCategoryForNewRecipeReply)mainMenu.ms.client.GetMessage();
					res_allItems.removeAllElements();
					allItemsModel.clear();
				for(int i=0;i<result.getAllItems().size();i++)
					{
						allItemsModel.addElement((String)result.getAllItems().get(i).get(1));  // display item names of chosen category in All Items JList
						res_allItems.add(result.getAllItems().get(i));
					}
					
				        tbl.repaint();
				    }	
				catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		});
		return catButt;
	}
	*/
		   	
	/**
	 * Method for creation panel that includes buttons "right" and "left" and JTextFields for any details of selected item
	 * (name of recipe,measure points ,quantity of item,cost of item,really cost of item) 
	 * @return middlePanel
	 */	
	private JPanel getMiddlePanel()                                 
	{
		middlePanel=new JPanel();
		GridBagLayout gbl = new GridBagLayout();    
		middlePanel.setLayout(gbl);
		GridBagConstraints gbc1 = new GridBagConstraints();
		GridBagConstraints gbc2 = new GridBagConstraints();
		GridBagConstraints gbc3 = new GridBagConstraints();
		GridBagConstraints gbc4 = new GridBagConstraints();
		GridBagConstraints gbc5 = new GridBagConstraints();
		GridBagConstraints gbc6 = new GridBagConstraints();
		GridBagConstraints gbc7 = new GridBagConstraints();
		GridBagConstraints gbc8 = new GridBagConstraints();
		GridBagConstraints gbc9 = new GridBagConstraints();
		GridBagConstraints gbc10 = new GridBagConstraints();
		GridBagConstraints gbc11 = new GridBagConstraints();
		GridBagConstraints gbc12 = new GridBagConstraints();
		GridBagConstraints gbc13 = new GridBagConstraints();
		GridBagConstraints gbc14 = new GridBagConstraints();
		GridBagConstraints gbc15 = new GridBagConstraints();
		
		
		
		gbc1.fill=GridBagConstraints.HORIZONTAL;
		gbc1.gridheight=1;
		gbc1.gridwidth=0;
		gbc1.insets = new Insets(0,0,50,0);
		
		gbc4.fill=GridBagConstraints.HORIZONTAL;
		gbc4.gridheight=1;
		gbc4.gridwidth=0;
		gbc4.insets = new Insets(0,0,50,0);
	
		
		gbc2.gridheight=1;
		gbc2.gridwidth=0;
		gbc2.insets = new Insets(0,0,0,0);
		
		gbc6.gridheight=1;
		gbc6.gridwidth=0;
		gbc6.insets = new Insets(0,0,0,0);
				
		gbc5.gridheight=1;
		gbc5.gridwidth=0;
		gbc5.insets = new Insets(0,0,20,0);
				
		gbc3.gridheight=1;
		gbc3.gridwidth=0;
		gbc3.insets = new Insets(0,0,20,0);
				
		gbc7.gridheight=1;
		gbc7.gridwidth=0;
		gbc7.insets = new Insets(0,0,0,0);
		
		gbc8.gridheight=1;
		gbc8.gridwidth=0;
		gbc8.insets = new Insets(0,0,20,0);
		
		gbc9.gridheight=1;
		gbc9.gridwidth=0;
		gbc9.insets = new Insets(0,0,0,0);
		
		gbc10.gridheight=1;
		gbc10.gridwidth=0;
		gbc10.insets = new Insets(0,0,20,0);
				
		gbc11.gridheight=1;
		gbc11.gridwidth=0;
		gbc11.insets = new Insets(0,0,0,0);
		
		gbc12.gridheight=1;
		gbc12.gridwidth=0;
		gbc12.insets = new Insets(0,0,20,0);
		
		gbc13.gridheight=1;
		gbc13.gridwidth=0;
		gbc13.insets = new Insets(0,0,0,0);
		
		gbc14.gridheight=1;
		gbc14.gridwidth=0;
		gbc14.insets = new Insets(0,0,70,0);
		
		gbc15.anchor = GridBagConstraints.NORTHWEST; 
		gbc15.fill   = GridBagConstraints.NONE;  
		gbc15.gridheight = 1;
		gbc15.gridwidth  = 1;
		gbc15.gridx = GridBagConstraints.RELATIVE; 
		gbc15.gridy = GridBagConstraints.RELATIVE; 
		gbc15.insets = new Insets(10, 10, 20, 0);
		
	/*	gbc15.gridheight=1;
		gbc15.gridwidth=0;
		gbc15.gridx=1;
		gbc15.insets = new Insets(0,0,0,0);*/
		
		JLabel catItemLbl=new JLabel("קטגוריה :");
		middlePanel.add(catItemLbl,gbc13);
		middlePanel.add(getCategoryItem(),gbc14);	
		
		
				
		middlePanel.add(getRightButton(),gbc1);

		middlePanel.add(getLeftButton(),gbc4);
		
		JLabel nameItemLbl=new JLabel("שם המוצר :");
		middlePanel.add(nameItemLbl,gbc2);
		middlePanel.add(getRecipeTxt(),gbc5);	

		JLabel measureItemLbl=new JLabel("יח' מדידה :");
		middlePanel.add(measureItemLbl,gbc6);		
		middlePanel.add(getMedidaTxt(),gbc3);
		
		JLabel reallyCostLbl=new JLabel("עלות כללית ליח' מדידה :");
		middlePanel.add(reallyCostLbl,gbc11);
		middlePanel.add(getReallyCostItemTxt(),gbc12);
		
		gbl.setConstraints(getButtInc(), gbc15);
		gbl.setConstraints(getButtDec(), gbc15);
        middlePanel.add(getButtInc(),gbc15);
		middlePanel.add(getButtDec(),gbc15);
		JLabel tWeightLbl=new JLabel("משקל : ");
		middlePanel.add(tWeightLbl,gbc7);
		middlePanel.add(getWeightTxt(),gbc8);
		
			
		
		JLabel costLbl=new JLabel("עלות לפי חישוב המערכת :");
		middlePanel.add(costLbl,gbc9);
		middlePanel.add(getCostItemTxt(),gbc10);
		
		
				
	return middlePanel;
	}
	
	
	/**
	 * Method for creation JComboBox categoryItem for sorting all the items by  the categories
	 * @return JButton catButt
	 */	
	private JComboBox getCategoryItem()
	{
	
	JComboBox	categoryItem =new JComboBox(new ConstantObjects().getItemCategories());
	categoryItem.addActionListener(new java.awt.event.ActionListener() 
		  	{
				public void actionPerformed(java.awt.event.ActionEvent e) {
					int a;
					int b;
					DefaultListModel tempModel  ;
					tempModel=new DefaultListModel();
					JComboBox roleBox = (JComboBox)e.getSource();
				    String selectedRole = (String)roleBox.getSelectedItem(); 
				    MessageGetItemsByCategoryForNewRecipe getItems=new MessageGetItemsByCategoryForNewRecipe(selectedRole);
					try {
												
						mainMenu.ms.client.sendToServer(getItems);	
						MessageGetItemsByCategoryForNewRecipeReply result=(MessageGetItemsByCategoryForNewRecipeReply)mainMenu.ms.client.GetMessage();
						if(nameTF1.getText().isEmpty())
						{filterByName1("");}
						else
						{
							filterByName1(nameTF1.getText());
							
						}
								for(int c=0;c<allItemsModel.getSize();c++)
								{
									tempModel.addElement( allItemsModel.get(c));	
									
								}
												
						
						allItemsModel.removeAllElements();
													
							for(a=0;a<tempModel.size();a++)
							{
								for(b=0;b<result.getAllItems().size();b++)
								{
									
									if(tempModel.get(a).equals(result.getAllItems().get(b).get(1)))
									{
										allItemsModel.addElement( tempModel.get(a));
										break;
									}
									
									
								}
								
								
							}
							
													
						}
					catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				
					} 
			});	
		return categoryItem;
	}
/**
 * Two buttons for increasing and decreasing of weight of item	
 * @return
 */
	private JButton getButtInc()
	{
	    
	    buttInc = new JButton("-");
		buttInc.addActionListener(new java.awt.event.ActionListener() 
	  	{
			public void actionPerformed(java.awt.event.ActionEvent e) {
				float temp;
				
				if(weightTxt.getText().isEmpty())
					weightTxt.setText("0.1")	;
				
				    temp=(Float.parseFloat(weightTxt.getText())-(float)(0.1));
				    if((temp<0))
						return;
				    
				    weightTxt.setText( Float.toString( temp)) ;
				    weightTxt.setText(new DecimalFormat("##.#").format(Float.parseFloat(weightTxt.getText())));
				    MessageGetPriceItemByNameItem msgShowPrice=new MessageGetPriceItemByNameItem(itemTxt.getText() );
					
					try {
						mainMenu.ms.client.sendToServer(msgShowPrice);
						MessageGetPriceItemByNameItemReply resultID=(MessageGetPriceItemByNameItemReply)mainMenu.ms.client.GetMessage();
						price=Float.parseFloat(resultID.getItemPrice());	
					    price=price*(Float.parseFloat(weightTxt.getText()));
					    costItemTxt.setText(new DecimalFormat("##.##").format(price));
					   // reallyCostItemTxt.setText(Float.toString(price));
					} catch (IOException e1) {
						
						e1.printStackTrace();
					}
				
			
				} 
		});	
		return buttInc;
	}
	
	private JButton getButtDec()
	{
	    buttDec = new JButton("+");
		buttDec.addActionListener(new java.awt.event.ActionListener() 
	  	{
			public void actionPerformed(java.awt.event.ActionEvent e) {
				if(weightTxt.getText().isEmpty())
				weightTxt.setText("0.1")	;
				weightTxt.setText( Float.toString( (Float.parseFloat(weightTxt.getText())+(float)(0.1)))) ;
				weightTxt.setText(new DecimalFormat("##.#").format(Float.parseFloat(weightTxt.getText())));
				MessageGetPriceItemByNameItem msgShowPrice=new MessageGetPriceItemByNameItem(itemTxt.getText() );
				
				try {
					mainMenu.ms.client.sendToServer(msgShowPrice);
					MessageGetPriceItemByNameItemReply resultID=(MessageGetPriceItemByNameItemReply)mainMenu.ms.client.GetMessage();
					price=Float.parseFloat(resultID.getItemPrice());	
				    price=price*(Float.parseFloat(weightTxt.getText()));
				    costItemTxt.setText(new DecimalFormat("##.##").format(price));
				   // reallyCostItemTxt.setText(Float.toString(price));
				} catch (IOException e1) {
					
					e1.printStackTrace();
				}
			
				} 
		});	
		return buttDec;
	}
	
	/**
	 * Methods for creation JTextFields for any details of selected recipe
	 * (name of item,measurement points,quantity of item,cost of item,really cost of item,)
	 * @return JTextFields ...
	 * 
	 */
//-------------------------------------------------------------------------------------------	
	private JTextField getRecipeTxt()
	{
		itemTxt=new JTextField();
		itemTxt.setHorizontalAlignment(JTextField.RIGHT);
		itemTxt.setColumns(10);
		itemTxt.setEditable(false);

	return itemTxt;
	}
	
	
	private JTextField getWeightTxt()
	{
		weightTxt=new JTextField();
		weightTxt.setHorizontalAlignment(JTextField.RIGHT);
		weightTxt.setColumns(10);
		weightTxt.addKeyListener(keyListener1);
		
	return weightTxt;
	}
	
//=========================================================	KeyListener for the JTextField weightTxt (quantity of anything item)========================================
	/**
	 * KeyListener for the JTextField weightTxt (quantity of anything item) for calculate cost of selected item by quantity
	 */
	KeyListener keyListener1 = new KeyListener() 
	{		      
		public void keyPressed(KeyEvent arg1) {}
			
				
		         
		public void keyReleased(KeyEvent arg0) 
		{
			JTextField nameField = (JTextField)arg0.getSource();
			String selectedName = (String)nameField.getText();
			
			if(selectedName.length()==0)
			{
				weightTxt.setBackground(Color.white);
				MessageGetPriceItemByNameItem msgShowPrice=new MessageGetPriceItemByNameItem( "0" );
			}
			
			for(int i=0;i<selectedName.length();i++)
			{
			if (selectedName.charAt(i) <'0'|| selectedName.charAt(i)>'9')
    		 {
    			 if(selectedName.charAt(i)=='.')
    				 break;
				//weightTxt.setBackground(Color.RED);
				 break;
    		 }
			
			else
			{
				
				MessageGetPriceItemByNameItem msgShowPrice=new MessageGetPriceItemByNameItem(itemTxt.getText() );
				
				try {
					mainMenu.ms.client.sendToServer(msgShowPrice);
					MessageGetPriceItemByNameItemReply resultID=(MessageGetPriceItemByNameItemReply)mainMenu.ms.client.GetMessage();
					price=Float.parseFloat(resultID.getItemPrice());	
				    price=price*(Float.parseFloat(weightTxt.getText()));
				    costItemTxt.setText(Float.toString(price));
				   
				  //  reallyCostItemTxt.setText(Float.toString(price));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				weightTxt.setBackground(Color.pink);
			}
			
			}			
			}
		
		public void keyTyped(KeyEvent arg0) {}		
	};
	
//====================================================================================================================================================================	
	
	
	private JTextField getMedidaTxt()
	{
		medidaTxt=new JTextField();
		medidaTxt.setHorizontalAlignment(JTextField.RIGHT);
		medidaTxt.setColumns(10);
		medidaTxt.setEditable(false);
		
	return medidaTxt;
	}
	
	
	private JTextField getCostItemTxt()
	{
		costItemTxt=new JTextField();
		costItemTxt.setHorizontalAlignment(JTextField.RIGHT);
		costItemTxt.setColumns(10);
		costItemTxt.setEditable(false);

	return costItemTxt;
	}
	
	private JTextField getReallyCostItemTxt()
	{
		reallyCostItemTxt=new JTextField();
		reallyCostItemTxt.setHorizontalAlignment(JTextField.RIGHT);
		reallyCostItemTxt.setColumns(10);

	return reallyCostItemTxt;
	}
	
	/**
	 * Method for creation JButton 	rightButton that transfer selected item from JList with all items to JList with 
	 * selected items  of new recipe
	 * @return rightButton
	 */
	private JButton getRightButton()
	{
		
		rightButton=new JButton("--->");
		res_recipeItems = new Vector<RecipeRightList>();
		rightButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				
			String selectedItem=(String)allItemsList.getSelectedValue();
			String selectedItem2=(String)menuItemsList.getSelectedValue();
			
				if (selectedItem!=null)
				{
					if(weightTxt.getText().isEmpty()){
			    		 JOptionPane.showMessageDialog(null,"יש לקבוע כמות המוצר");
			    		 return;	
			    				 }
					if (weightTxt.getText().charAt(0)=='.' )
					{
						JOptionPane.showMessageDialog(null,"כמות לא חוקית");
					            return;}
					else{
					try{
						
						float f=Float.parseFloat(weightTxt.getText());
						
					}catch(NumberFormatException e1)
					{
						
						JOptionPane.showMessageDialog(null,"יש להקיש ספרות בלבד");
						weightTxt.setText("");
						return;
					}
					
					
					
						
					
					totalPrice=totalPrice+Float.parseFloat(costItemTxt.getText());
					totalWeight=totalWeight+Float.parseFloat(weightTxt.getText());
					
					
					Float weight=(Float.parseFloat(weightTxt.getText()));
					String costItem=costItemTxt.getText();
					String medida=medidaTxt.getText();
					String reallyCostItem=reallyCostItemTxt.getText();
					costTxt.setText(new DecimalFormat("##.##").format(totalPrice));
					mishkalMatkon.setText(new DecimalFormat("##.#").format(totalWeight));
					mishkalTxt.setText(Float.toString(totalWeight));
					allItemsModel.removeElement(selectedItem);
					recipeItemsModel.addElement(selectedItem);
			            	for(int i=0; i<res_allItems.size();i++)
					{
					     if(res_allItems.get(i).getItemName().equals(selectedItem))
					     {
					    	 RecipeRightList row=new RecipeRightList();
					    	 row.setItemName((String) res_allItems.get(i).getItemName());                
					    	 row.setiCost(Float.parseFloat(reallyCostItem)) ;
					    	 row.setiReallyCost(Float.parseFloat(costItem)) ;	                                     
					    	 row.setiUnit_of_measure((String) res_allItems.get(i).getIUnit_of_measure());                
					    	 row.setiQuantity(weight) ;					    	                   
					    	 row.setItemID( res_allItems.get(i).getItemID());                 
					    	 res_recipeItems.add(row);	
					    	
								NotEdditibleTable orderModel = (NotEdditibleTable) (tbl
										.getModel());
					    	 
					    		orderModel.setDataVector(parseVectorObjectToVectorVector(res_recipeItems), tblheader);
					    		
					    		
					    		tbl.setModel(orderModel);
					    		for(int x=0;x<5;x++){
									tbl.getColumnModel().getColumn(x).setCellRenderer( centerRenderer );
							        }
					    	    res_allItemsTemp.add(res_allItems.get(i));
					    	    res_allItems.remove(i);
					    	 medidaTxt.setText("");
					    	 weightTxt.setText("");
					    	 costItemTxt.setText("");
					    	 reallyCostItemTxt.setText("");
					    	
					    	break;
					     					    	
					     					
					}
					
					}
					}}		
				else
				{
					if (selectedItem2!=null)
					{
					int j;
					for(j=0; j<res_recipeItems.size();j++)
					{
					     if(res_recipeItems.get(j).getItemName().equals(itemTxt.getText()))
					     {
					    	 if(weightTxt.getText().isEmpty()){
					    		 JOptionPane.showMessageDialog(null,"יש לקבוע כמות המוצר");
					    		 return;	
					    				 }
							else{
							totalPrice=(totalPrice- res_recipeItems.get(j).getiReallyCost())+Float.parseFloat(costItemTxt.getText());
							totalWeight=(totalWeight- res_recipeItems.get(j).getiQuantity())+Float.parseFloat(weightTxt.getText());
						
							res_recipeItems.get(j).setiReallyCost(Float.parseFloat(costItemTxt.getText()));       //Cost of item this 
							res_recipeItems.get(j).setiQuantity(Float.parseFloat( weightTxt.getText()));           //Quantity of item this
							
						
							costTxt.setText(Float.toString(totalPrice));
							mishkalTxt.setText(Float.toString(totalWeight));
							mishkalMatkon.setText(Float.toString(totalWeight));
							NotEdditibleTable orderModel = (NotEdditibleTable) (tbl
									.getModel());
				    	 
				    		orderModel.setDataVector(parseVectorObjectToVectorVector(res_recipeItems), tblheader);
				    	
				    		tbl.setModel(orderModel);
				    		for(int x=0;x<5;x++){
								tbl.getColumnModel().getColumn(x).setCellRenderer( centerRenderer );
						        }
							}			    	                   
						
					    	
					     }
					    
					}
					}
					else
					{
						JOptionPane.showMessageDialog(null,"יש לבחור פריט");
			    		 return;
					}
						
					}
					
					
					
					
				}
						
			
			
		});
			
		return rightButton;		
	}
	
	
	private Vector<Vector> parseVectorObjectToVectorVector (Vector<RecipeRightList> vectorObj)
	{
		Vector<Vector> vectorvector=new Vector<Vector>();
		for(int i=0;i<vectorObj.size();i++)
		{
			Vector<String> vector=new Vector<String>();
			vector.add(vectorObj.get(i).getItemName());
			vector.add(Float.toString(vectorObj.get(i).getiCost()));
			vector.add(Float.toString(vectorObj.get(i).getiReallyCost()));
		   
		    vector.add(vectorObj.get(i).getiUnit_of_measure());
			vector.add(Float.toString(vectorObj.get(i).getiQuantity()));
			vectorvector.add(vector);
		}
		
		return vectorvector;
		
		
		
	}

	/**
	 * Method for creation JButton 	leftButton that transfer selected item from JList with selected items  of new recipe 
	 * to JList with all items that restaurant has
	 * 
	 * @return leftButton
	 */
	private JButton getLeftButton()
	{
		leftButton=new JButton("<---");
		leftButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				
				String selectedItem=(String)menuItemsList.getSelectedValue();
				if (selectedItem!=null)
				{
					recipeItemsModel.removeElement(selectedItem);
					allItemsModel.addElement(selectedItem);
					for(int i=0; i<res_recipeItems.size();i++)
					{
					     if(res_recipeItems.get(i).getItemName().equals(selectedItem))
					     {
					    	 
					    	 totalPrice=(totalPrice)-( res_recipeItems.get(i).getiReallyCost());
					    	 costTxt.setText(new DecimalFormat("##.##").format(totalPrice));
					    	 totalWeight=totalWeight- res_recipeItems.get(i).getiQuantity();
					    	 mishkalTxt.setText(String.valueOf(totalWeight));
					    	 mishkalMatkon.setText(new DecimalFormat("##.#").format(totalWeight));
					    	 
					    	 itemTxt.setText("");
					    	 medidaTxt.setText("");
					    	 costItemTxt.setText("");
					    	 costItemTxt.setText("");
					    	 weightTxt.setText("");
					    	 reallyCostItemTxt.setText("");
					    	 res_recipeItems.remove(i);
					    	
					    	 for(int j=0;j<res_allItemsTemp.size();j++)
					    	 {
					    		 
					    		if(res_allItemsTemp.get(j).getItemName().equals(selectedItem))
					    		 {
					    			 res_allItems.add(res_allItemsTemp.get(j));
					    			 res_allItemsTemp.remove(j);
					    			 break;
					    		 }
					    	 }
					    	 NotEdditibleTable orderModel = (NotEdditibleTable) (tbl
										.getModel());
					    	 
					    		orderModel.setDataVector(parseVectorObjectToVectorVector(res_recipeItems), tblheader);
					    	
					    		tbl.setModel(orderModel);
					    		
					    		for(int x=0;x<5;x++){
									tbl.getColumnModel().getColumn(x).setCellRenderer( centerRenderer );
							        }
					    	 
					    	break;
					     }
					}
					tbl.repaint();
				} 
				
				else
				{
					JOptionPane.showMessageDialog(null,"יש לבחור פריט");
				}
						
			}
		});
		
		return leftButton;		
	}
	
	
	//=====================panels for rightPanel ============================================	
	/**Method for creation JPanel rightPanel that consists of  3 panels (DetailsPanel,TablePanel,ButtonsPanel)
	 * return rightPanel
	 */	
	private JPanel getRightPanel()
	{
		rightPanel=new JPanel();
		rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
		rightPanel.add(getDetailsPanel());            // panel with buttons for getting details for new recipe
		rightPanel.add(getTablePanel());             // panel with items table
		rightPanel.add(getButtonsPanel());           // panel with save and cancel buttons 
		
	return rightPanel;
	}
	
	/**
	 * Method for creation JPanel tablePanel that includes JTable tbl with items of this  recipe(all items that we see them in 
	 * recipeItemsListPanel )
	 * @return tablePanel
	 */
	private JPanel getTablePanel()
	{
		tablePanel=new JPanel();
		tablePanel.setBorder(new TitledBorder(null, "טבלת מוצרים שנבחרו למתכון ", TitledBorder.CENTER, TitledBorder.TOP, null, null));
	    tblheader=new Vector<String>();
	    tblheader.add("מוצר");
		tblheader.add("עלות כללית");
		tblheader.add("עלות נבחרת");
		tblheader.add("יח מדידה");
		tblheader.add("משקל");
		
		
		dtm=new NotEdditibleTable(parseVectorObjectToVectorVector(res_recipeItems),tblheader);	 	
		tbl = new JTable(dtm);
	    centerRenderer = new DefaultTableCellRenderer();
		centerRenderer.setHorizontalAlignment( JLabel.CENTER );
		for(int x=0;x<5;x++){
			tbl.getColumnModel().getColumn(x).setCellRenderer( centerRenderer );
	        }
		tbl.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		tbl.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
		tbl.setFont(new Font("David", Font.BOLD, 16));
		tbl.getTableHeader().setFont( new Font( "Arial" , Font.BOLD, 17 ));
		tbl.getTableHeader().setBackground(new Color(173,216,230));
		tbl.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); 
		tbl.setFillsViewportHeight(true);
	    tbl.setRowHeight(40);
		tbl.setFillsViewportHeight(true);
        tbl.setGridColor(new Color(25, 25, 112));
        tbl.setBackground(new Color(255, 240, 245));
        tbl.setForeground(new Color(0, 0, 0));
        tbl.setAutoCreateRowSorter(true);
        
		
        JScrollPane scrollPane = new JScrollPane(tbl);
        scrollPane.setPreferredSize(new Dimension(500,400));
        tablePanel.add(scrollPane);
		
	return tablePanel;
	}
	
	/**
	 * Method for creation JPanel buttonsPanel that includes buttons for control of the new recipe(Save and Cancel)
	 * @return buttonsPanel
	 */
	private JPanel getButtonsPanel()
	{
		
		buttonsPanel=new JPanel();
		buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS));
		buttonsPanel.add(getSaveButton());
		buttonsPanel.add(Box.createHorizontalStrut(25));
		buttonsPanel.add(getCancelButton());
		
	return buttonsPanel;
		
	}
	
	/**
	 * Method for creation JButton saveButton  for saving of the new recipe in database
	 * @return saveButton
	 */
	private JButton getSaveButton()
	{
		final Vector<String> arr = new Vector<String>();
		//send it to class PanelFunctionListOfAllRecipes(right side panel) for to know that any recipe is not chosen yet(empty vector)
		JButton saveButton=new JButton("שמור");
		saveButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				System.out.println("SAVE"+options);
				int result1;
				result1=inputCheck();		
				if(result1==0)
				{
							 Vector<String>	recipeDetails = new Vector<String>();
							 recipeDetails.add(textField_RecipeId.getText());							
							 recipeDetails.add(textField_nameRecipe.getText());							
							 recipeDetails.add(textField_price.getText());
							 recipeDetails.add(flag);
							 recipeDetails.add(mishkalMatkon.getText());
							 recipeDetails.add(options.get(0));	        //check exist meidat asiya
							 if(options.get(1)=="0")
								 recipeDetails.add("0"); 
							 else 
								 recipeDetails.add("6"); 
							 if(options.get(2)=="0")
								 recipeDetails.add("0"); 
							 else 
								 recipeDetails.add("6"); 
								 
							 
												
							 MessageAddRecipeToDataBase msgNewRecipe= new MessageAddRecipeToDataBase(res_recipeItems,recipeDetails);
					try {
						mainMenu.ms.client.sendToServer(msgNewRecipe);
						MessageSavingReply result = (MessageSavingReply)mainMenu.ms.client.GetMessage();
						
				    	if (result.getResult()== '0')
				    	{
				    		JOptionPane.showMessageDialog(null,"בעיית תקשורת 03");
				    	}
				    	
				    	else 
				    	{
				    		JOptionPane.showMessageDialog(null,"הנתונים נשמרו בהצלחה");
				    	}
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					MessageGetAllRecipes msgShowMenu=new MessageGetAllRecipes( );
					
					try {
						mainMenu.ms.client.sendToServer(msgShowMenu);
						MessageGetAllRecipesReply resultMenu=(MessageGetAllRecipesReply)mainMenu.ms.client.GetMessage();
					mainMenu.getContentPane().remove(((BorderLayout)mainMenu.getContentPane().getLayout()).getLayoutComponent(BorderLayout.CENTER));
					mainMenu.getContentPane().add(new PfShow_all_recipes(mainMenu,resultMenu.getRecipes()), BorderLayout.CENTER);	
					mainMenu.getContentPane().remove(((BorderLayout)mainMenu.getContentPane().getLayout()).getLayoutComponent(BorderLayout.EAST));
					mainMenu.getContentPane().add(new PanelFunctionListOfAllRecipes(mainMenu, arr), BorderLayout.EAST);
					mainMenu.getContentPane().validate();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
				
			}
		});
	return saveButton;
	}
	
	/**
	 * Method for creation JButton cancelButton  for an exit from this window without saving of new recipe
	 * @return
	 */
	private JButton getCancelButton()
	{
		JButton cancelButton=new JButton("ביטול");
		cancelButton.addActionListener(new java.awt.event.ActionListener() 
		   {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{
                    MessageGetAllRecipes msgShowMenu=new MessageGetAllRecipes( );
				
				try {
					mainMenu.ms.client.sendToServer(msgShowMenu);
					MessageGetAllRecipesReply resultMenu=(MessageGetAllRecipesReply)mainMenu.ms.client.GetMessage();
				mainMenu.getContentPane().remove(((BorderLayout)mainMenu.getContentPane().getLayout()).getLayoutComponent(BorderLayout.CENTER));
				mainMenu.getContentPane().add(new PfShow_all_recipes(mainMenu,resultMenu.getRecipes()), BorderLayout.CENTER);	
				//mainMenu.getContentPane().remove(((BorderLayout)mainMenu.getContentPane().getLayout()).getLayoutComponent(BorderLayout.EAST));
				//mainMenu.getContentPane().add(new PanelFunctionMenuAllStandartsMenu(mainMenu), BorderLayout.EAST);
				mainMenu.getContentPane().validate();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		
	return cancelButton;
	}
	
	/**
	 * Method for creation JScrollPane that include detailsPanel that includes JTextFields for filling of data of the new recipe(ID,name,price)and JComboBox 
	 * for  a status choice
	 * @return detailsPanel
	 */
	private JScrollPane getDetailsPanel()
	{
		detailsPanel=new JPanel();
		detailsPanel.setBorder(new TitledBorder(null, "פרטי המתכון ", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		detailsPanel.setLayout(new SpringLayout());
		textField_RecipeId = new JTextField();
		textField_RecipeId.setHorizontalAlignment(JTextField.RIGHT);
		textField_RecipeId.setFont(new Font("Tahoma", Font.PLAIN, 16));
		textField_RecipeId.setSize(new Dimension(20,30));
		MessageShowIDRecipe msgShowID=new MessageShowIDRecipe( );
		try {
			mainMenu.ms.client.sendToServer(msgShowID);
			MessageShowIDRecipeReply resultID=(MessageShowIDRecipeReply)mainMenu.ms.client.GetMessage();
		    mId=Integer.parseInt(resultID.getResultID());	
			
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		
		 mId=mId+1;
		 textField_RecipeId.setText(Integer.toString(mId));
		 textField_RecipeId.setColumns(10);
		 textField_RecipeId.setEditable(false);
		 textField_RecipeId.setBackground(Color.pink);
		
		JLabel rid = new JLabel("מספר המתכון:", JLabel.TRAILING);
		rid.setForeground(new Color(75, 0, 130));
		rid.setFont(new Font("Tahoma", Font.BOLD, 12));
		rid.setLabelFor(textField_RecipeId);
		
		detailsPanel.add(textField_RecipeId);
		detailsPanel.add(rid);
		
		textField_nameRecipe = new JTextField();
		textField_nameRecipe.setHorizontalAlignment(JTextField.RIGHT);
		textField_nameRecipe.setFont(new Font("Tahoma", Font.PLAIN, 13));
		textField_nameRecipe.setColumns(10);	
		
		JLabel name = new JLabel("שם המתכון:", JLabel.TRAILING);
		name.setForeground(new Color(75, 0, 130));
		name.setFont(new Font("Tahoma", Font.BOLD, 12));
		name.setLabelFor(textField_nameRecipe);	
		//======================================================CHECK FOR CORRECT INPUT NAME==================================================
		/**
		 * CHECK FOR CORRECT INPUT NAME
		 */
		KeyListener keyListener1 = new KeyListener() 
		{		      
			public void keyPressed(KeyEvent arg0) {}

			public void keyReleased(KeyEvent arg0) 
			{
				JTextField nameField1 = (JTextField)arg0.getSource();
				String selectedName1 = (String)nameField1.getText();
				if(selectedName1.length()==0)
				{
					textField_nameRecipe.setBackground(Color.white);
				}
				for(int i=0;i<selectedName1.length();i++)
				{
				
					textField_nameRecipe.setBackground(Color.pink);
				
				}
			}

			public void keyTyped(KeyEvent arg0) {}		
		};	
		textField_nameRecipe.addKeyListener(keyListener1);		
		
		//======================================================================================================================
		
		detailsPanel.add(textField_nameRecipe);
		detailsPanel.add(name);
		
		 mishkalMatkon = new JTextField();
		mishkalMatkon.setHorizontalAlignment(JTextField.RIGHT);
		mishkalMatkon.setFont(new Font("Tahoma", Font.PLAIN, 13));
		mishkalMatkon.setColumns(10);
		JLabel labelMishkal = new JLabel("משקל מתכון (בק''ג) :", JLabel.TRAILING);
		labelMishkal.setForeground(new Color(75, 0, 130));
		labelMishkal.setFont(new Font("Tahoma", Font.BOLD, 12));
		labelMishkal.setLabelFor(mishkalMatkon);
		detailsPanel.add(mishkalMatkon);
		detailsPanel.add(labelMishkal);
		//===========================================CHECK FOR CORRECT INPUT MISHKAL==================================================
				
				
				KeyListener keyListener2 = new KeyListener() 
				{		      
					public void keyPressed(KeyEvent arg0) {}

					public void keyReleased(KeyEvent arg0) 
					{
						JTextField mishkalField = (JTextField)arg0.getSource();
						String selectedName = (String)mishkalField.getText();
						if(selectedName.length()==0)
						{
							mishkalMatkon.setBackground(Color.white);
						}
						try{
							
							float f=Float.parseFloat(mishkalMatkon.getText());
							mishkalMatkon.setBackground(Color.pink);
							
						}catch(NumberFormatException e1)
						{
							
							mishkalMatkon.setBackground(Color.red);
							
						}
						
					}

					public void keyTyped(KeyEvent arg0) {}		
				};
				
				mishkalMatkon.addKeyListener(keyListener2);	
		
	//---------------------------------------------------------------------------------------------------------------------	
		
		
		textField_price = new JTextField();
		textField_price.setHorizontalAlignment(JTextField.RIGHT);
		textField_price.setFont(new Font("Tahoma", Font.PLAIN, 13));
		textField_price.setColumns(10);
		
		JLabel labelPrice = new JLabel("הוצאות נלוות(קבוע בש''ח):", JLabel.TRAILING);
		labelPrice.setForeground(new Color(75, 0, 130));
		labelPrice.setFont(new Font("Tahoma", Font.BOLD, 12));
		labelPrice.setLabelFor(textField_price);
		
	//===========================================CHECK FOR CORRECT INPUT PRICE==================================================
		/**
		 * CHECK FOR CORRECT INPUT PRICE
		 */
		
		KeyListener keyListener = new KeyListener() 
		{		      
			public void keyPressed(KeyEvent arg0) {}

			public void keyReleased(KeyEvent arg0) 
			{
				JTextField nameField = (JTextField)arg0.getSource();
				String selectedName = (String)nameField.getText();
				if(selectedName.length()==0)
				{
					textField_price.setBackground(Color.white);
				}
				try{
					
					float f=Float.parseFloat(textField_price.getText());
					textField_price.setBackground(Color.pink);
					
				}catch(NumberFormatException e1)
				{
					
					textField_price.setBackground(Color.red);
					
				}
			}

			public void keyTyped(KeyEvent arg0) {}		
		};
		
		textField_price.addKeyListener(keyListener);	
	//=============================================================================================================================
		detailsPanel.add(textField_price);
		detailsPanel.add(labelPrice);
	   	
		
		
				
		JLabel labelOptions = new JLabel("הגדרות נוספות:", JLabel.TRAILING);
		labelOptions.setForeground(new Color(75, 0, 130));
		labelOptions.setFont(new Font("Tahoma", Font.BOLD, 12));
		labelOptions.setLabelFor(getAddOptionsForRecipeButt());
		detailsPanel.add(getAddOptionsForRecipeButt());
		detailsPanel.add(labelOptions);	
		
		
		JLabel label_1 = new JLabel("סטטוס:", JLabel.TRAILING);
		label_1.setForeground(new Color(75, 0, 130));
		label_1.setFont(new Font("Tahoma", Font.BOLD, 12));
		label_1.setLabelFor(statusRecipe);
		
		//===========================================CHECK FOR CORRECT INPUT status==================================================
		
		/**
	   	 * CHECK FOR CORRECT INPUT status
	   	 */
		statusRecipe=new JComboBox(new ConstantObjects().getMenuStatus());
		statusRecipe.addActionListener(new java.awt.event.ActionListener() 
		  	{
				public void actionPerformed(java.awt.event.ActionEvent e) {
					JComboBox roleBox = (JComboBox)e.getSource();
				    String selectedRole = (String)roleBox.getSelectedItem(); 
				    if(selectedRole.equals("פעיל") || selectedRole.equals("לא פעיל"))
				    {
				    	if(selectedRole.equals("פעיל"))
				    		flag="פעיל";
				    	else
				    		flag="לא פעיל";
				    					  
				    	statusRecipe.setBackground(Color.pink);
				  
			    	}
				    else
				    {
				    	
				    	statusRecipe.setBackground(Color.RED);
				    }
				
					} 
			});	
		
		//============================================================================================================================
		detailsPanel.add(statusRecipe);
		detailsPanel.add(label_1);	
			
			JScrollPane scrollPane = new JScrollPane(detailsPanel);
	        scrollPane.setPreferredSize(new Dimension(500,380));               //400,280
	     		     
		
		SpringUtilities.makeCompactGrid(detailsPanel, 6, 2, //rows, cols
			        x/17, y/100, //initX, initY                     //100,10
			        10, 5); //xPad, yPad                       //10,30//x/160,y/33
		
	return scrollPane;
	}
	
	
	private JButton getAddOptionsForRecipeButt()
	{
		options = new  Vector<String> ();
		JButton addOptionsForRecipeButt = new JButton("הוסיף הגדרות:");
		addOptionsForRecipeButt.setHorizontalAlignment(JTextField.RIGHT);
		addOptionsForRecipeButt.setFont(new Font("Tahoma", Font.PLAIN, 13));
		addOptionsForRecipeButt.setPreferredSize(new Dimension(30,30));
		for(int i=0;i<3;i++)
			options.add(i, "0");
		addOptionsForRecipeButt.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				
				
			    addItem = new PfAdd_options_for_recipe(options);
					
					
			
				
			}
		});
		
		return addOptionsForRecipeButt;
	}
	
	
	
	
	
	/**
	 * Method for check correctness of input
	 * @return Integer result
	 */
	private int inputCheck()
	 {
		int result=0;
		
		
		//=================================================check for empty price and name================================		
		
		
		String price=textField_price.getText();
		String name=textField_nameRecipe.getText();
		String selectedRole = (String)statusRecipe.getSelectedItem();
		String mishkalRecipe = mishkalMatkon.getText();
		
		if(price.isEmpty() && name.isEmpty())
		{
			JOptionPane.showMessageDialog(null,"יש להקיש שם ולקבוע עלות למתכון");	
			textField_nameRecipe.setBackground(Color.RED);
			textField_price.setBackground(Color.RED);
			result=1;
		}
		else
			if(price.isEmpty())
			{
				JOptionPane.showMessageDialog(null,"יש לקבוע עלות");	
				textField_price.setBackground(Color.RED);
				result=1;
			}
			else
			if(name.isEmpty())
			{
				JOptionPane.showMessageDialog(null,"יש לתת שם למתכון");	
				textField_nameRecipe.setBackground(Color.RED);
				result=1;
			}
		if( mishkalRecipe.isEmpty())
		{
			JOptionPane.showMessageDialog(null,"יש לקבוע את משקל המנה");	
			mishkalMatkon.setBackground(Color.RED);
			mishkalMatkon.setBackground(Color.RED);
			result=1;
		}
		
		//=================================================check for mishkal================================		
		if(result==0)
		{
			try{
				
				float f=Float.parseFloat(mishkalMatkon.getText());
				mishkalMatkon.setBackground(Color.pink);
				
			}catch(NumberFormatException e1)
			{
				
				JOptionPane.showMessageDialog(null,"משקל שגוי.יש להקיש ספרות בלבד");
				result=1;
				mishkalMatkon.setBackground(Color.RED);
				
			}
		
		
		}
		
		
		
		
		//=================================================check for price================================		
		/**
		 * check correctness of price
		 */		
		if(result==0)
		{
              try{
				
				float f=Float.parseFloat(textField_price.getText());
				textField_price.setBackground(Color.pink);
				
			     }
              catch(NumberFormatException e1)
			     {
				
				JOptionPane.showMessageDialog(null,"משקל שגוי.יש להקיש ספרות בלבד");
				result=1;
				textField_price.setBackground(Color.RED);
				
			      }
		
		
	 }
		
		//=================================================check for status================================		
		/**
		 * Check correctness of status
		 */
		if(result==0)
		{
		if(selectedRole.equals("פעיל") || selectedRole.equals("לא פעיל"))
	    {
	    	
			statusRecipe.setBackground(Color.pink);
	    		    	
    	}
	    else
	    {
	    	JOptionPane.showMessageDialog(null,"יש לבחור סטטוס");	
	    	statusRecipe.setBackground(Color.RED);
	    	result=1;
	    }
		
		}
		return result;
}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
private class PfAdd_options_for_recipe extends JFrame{
		
		private Vector<String> options;
		private JCheckBox meidatAsiyaCheckBox;
		private JCheckBox extraCheckBox;
		private JCheckBox souceCheckBox;
		private String tryString;
		
		
		public PfAdd_options_for_recipe(Vector<String> opt)
		{
			super();
			this.setSize(414, 344);
			this.options=opt;
			getContentPane().setLayout(null);
			initialize();
			this.setVisible(true);
		}
		
		

		public void initialize()
		{
			  Dimension sSize = Toolkit.getDefaultToolkit().getScreenSize();
			  this.setLocation((sSize.width-this.getWidth())/2,(sSize.height-this.getHeight())/2);
			  getContentPane().add(getDetailsPanel());
			  			
			 
			  
			  
			 
		}
		
		public  JPanel getDetailsPanel()
		{
			JPanel infoPanel=new JPanel();
			infoPanel.setLayout(null);
			
			  JLabel meidatAsiyaLabel = new JLabel("האם נדרש להגדיר למנה מידת עשיה:");
			  meidatAsiyaLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
			  meidatAsiyaLabel.setBounds(140, 47, 248, 38);
			  getContentPane().add(meidatAsiyaLabel);
			  
			  JLabel labelExtra = new JLabel("האם מנה יוצאת בליווי תוספות:");
			  labelExtra.setFont(new Font("Tahoma", Font.PLAIN, 12));
			  labelExtra.setBounds(140, 121, 248, 38);
			  getContentPane().add(labelExtra);
			  
			  JLabel labelSouce = new JLabel("האם מנה יוצאת בליווי רוטבים:");
			  labelSouce.setFont(new Font("Tahoma", Font.PLAIN, 12));
			  labelSouce.setBounds(140, 194, 248, 38);
			  getContentPane().add(labelSouce);
			  
			  meidatAsiyaCheckBox = new JCheckBox("");
			  
			  meidatAsiyaCheckBox.setBounds(62, 58, 34, 23);
			  getContentPane().add(meidatAsiyaCheckBox);
			  
			  
			  
			  extraCheckBox = new JCheckBox("");
			  extraCheckBox.setBounds(62, 136, 34, 23);
			  getContentPane().add(extraCheckBox);
			  
			  
			 
			  
			  souceCheckBox = new JCheckBox("");
			  souceCheckBox.setBounds(62, 209, 34, 23);
			  getContentPane().add(souceCheckBox);
			
			  if(options.get(0).equals("0")==false)
				  meidatAsiyaCheckBox.setSelected(true);
			  if(options.get(1).equals("0")==false)
				  extraCheckBox.setSelected(true);
			  if(options.get(2).equals("0")==false)
				  souceCheckBox.setSelected(true); 
			 
			  getContentPane().add(getSaveButton(this));
			  getContentPane().add(getCancelButton(this));
			  
			  JLabel lblNewLabel_1 = new JLabel("הגדרות נוספות למנה:");
			  lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 16));
			  lblNewLabel_1.setBounds(109, 11, 196, 35);
			  getContentPane().add(lblNewLabel_1);
			  
			return infoPanel;
		}
		
		public JButton getSaveButton(PfAdd_options_for_recipe opt)
		{
			final PfAdd_options_for_recipe optionsRecipe;
			optionsRecipe=opt;
			JButton saveButt = new JButton("שמור");
			saveButt.setBounds(73, 253, 89, 44);
				
			saveButt.setPreferredSize(new Dimension(70, 40));
			saveButt.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					
					  if( meidatAsiyaCheckBox.isSelected())
						  options.add(0, "1");
					  				  
					  else
						  options.add(0, "0");
					  if( extraCheckBox.isSelected())
						  options.add(1, "1");
					  else
						  options.add(1, "0");
					  
					  if( souceCheckBox.isSelected())
						  options.add(2, "1");
					  else
						  options.add(2, "0");
					  optionsRecipe.dispose();	
					  
					
				}	
			});
			return saveButt;
		}
		
		public JButton getCancelButton(PfAdd_options_for_recipe opt)
		{
			final PfAdd_options_for_recipe optionsRecipe;
			optionsRecipe=opt;
			  JButton cancelButt = new JButton("ביטול");
			  cancelButt.setBounds(248, 253, 89, 44);
			  cancelButt.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					optionsRecipe.dispose();	
					
				}
			});
			return cancelButt;
		}
		
		
	}

}
	
	
	
	
	

